package com.yao.dubboprovider.server;

import com.yao.dubboapi.entity.InvokeMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * @author Henry Yao
 * @since 2021/5/3
 */
public class NettyServerProviderHandler extends SimpleChannelInboundHandler<InvokeMessage> {

    private Map<String, Class<?>> providerMap;

    public NettyServerProviderHandler(Map<String, Class<?>> providerMap) {
        this.providerMap = providerMap;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, InvokeMessage msg) throws Exception {
        String className = msg.getClassName();
        if (providerMap.containsKey(className)) {
            doRpc(className, msg, ctx);
        } else {
            ctx.writeAndFlush("没有该服务：" + className);
        }
        ctx.close();
    }

    private void doRpc(String className, InvokeMessage message, ChannelHandlerContext ctx) throws NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
        Class<?> aClass = providerMap.get(className);
        Method method = aClass.getMethod(message.getMethodName(), message.getParameterTypes());
        Object o = method.invoke(aClass.newInstance(), message.getParameterValues());
        ctx.writeAndFlush(o);
    }
}
